import 'babel-polyfill'
import Vue from 'vue'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import 'normalize.css/normalize.css'
import NProgress from 'nprogress' // Progress 进度条
import 'nprogress/nprogress.css' // Progress 进度条样式
import App from './App'
import router from 'router'
import store from 'store'
import 'styles/index.styl'
import 'styles/icons'
import {getToken} from 'utils/auth'

Vue.use(ElementUI)
Vue.config.productionTip = false

// 不重定向白名单
const whiteList = ['/login']

router.beforeEach((to, from, next) => {
  NProgress.start()

  if (getToken()) {
    if (to.path === '/login') {
      next({path: '/'})
      NProgress.done()
    } else {
      if (store.getters.permissions.length === 0) {
        store
          .dispatch('GetUserInfo')
          .then(() => {
            const permissions = store.getters.permissions
            store.dispatch('GenerateRoutes', {permissions}).then(() => {
              // 动态添加可访问路由表
              router.addRoutes(store.getters.addRouters)
              next({...to, replace: true})
            })
          })
          .catch(e => {
            console.log(e)
            store.dispatch('RemoveToken').then(() => {
              next({path: '/login'})
            })
          })
      } else {
        next()
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  render: h => h(App)
})
